import { createStore } from "vuex";
import { websiteApi, articleApi, categoryApi, tagApi } from '@/utils/api'

// 状态接口定义
interface WebsiteInfo {
  name: string
  description: string
  author: string
  avatar: string
  // 添加其他网站信息字段
}

interface Article {
  id: number
  title: string
  content: string
  summary: string
  categoryId: number
  categoryName: string
  tags: string[]
  createTime: string
  updateTime: string
  viewCounts: number
  likeNum: number
  commentCounts: number
  isOriginal: number
  originalUrl?: string
  // 添加其他文章字段
}

interface Category {
  id: number
  name: string
  count: number
}

interface Tag {
  id: number
  name: string
  count: number
}

interface State {
  // 网站信息
  website: WebsiteInfo | null
  
  // 文章相关
  articles: Article[]
  currentArticle: Article | null
  newsArticles: Article[]
  
  // 分类和标签
  categories: Category[]
  tags: Tag[]
  
  // UI 状态
  loading: boolean
  sidebarCollapsed: boolean
  
  // 用户交互状态
  readingHistory: string[]
  favorites: string[]
}

export const store = createStore<State>({
  state(): State {
    return {
      website: null,
      articles: [],
      currentArticle: null,
      newsArticles: [],
      categories: [],
      tags: [],
      loading: false,
      sidebarCollapsed: false,
      readingHistory: [],
      favorites: []
    }
  },

  mutations: {
    // 网站信息
    SET_WEBSITE(state, website: WebsiteInfo) {
      state.website = website
    },
    
    // 文章相关
    SET_ARTICLES(state, articles: Article[]) {
      state.articles = articles
    },
    
    SET_CURRENT_ARTICLE(state, article: Article) {
      state.currentArticle = article
    },
    
    SET_NEWS_ARTICLES(state, articles: Article[]) {
      state.newsArticles = articles
    },
    
    // 分类和标签
    SET_CATEGORIES(state, categories: Category[]) {
      state.categories = categories
    },
    
    SET_TAGS(state, tags: Tag[]) {
      state.tags = tags
    },
    
    // UI 状态
    SET_LOADING(state, loading: boolean) {
      state.loading = loading
    },
    
    TOGGLE_SIDEBAR(state) {
      state.sidebarCollapsed = !state.sidebarCollapsed
    },
    
    SET_SIDEBAR_COLLAPSED(state, collapsed: boolean) {
      state.sidebarCollapsed = collapsed
    },
    
    // 用户交互
    ADD_TO_READING_HISTORY(state, articleId: string) {
      const index = state.readingHistory.indexOf(articleId)
      if (index > -1) {
        state.readingHistory.splice(index, 1)
      }
      state.readingHistory.unshift(articleId)
      // 限制历史记录数量
      if (state.readingHistory.length > 50) {
        state.readingHistory = state.readingHistory.slice(0, 50)
      }
    },
    
    TOGGLE_FAVORITE(state, articleId: string) {
      const index = state.favorites.indexOf(articleId)
      if (index > -1) {
        state.favorites.splice(index, 1)
      } else {
        state.favorites.unshift(articleId)
      }
    },
    
    SET_FAVORITES(state, favorites: string[]) {
      state.favorites = favorites
    }
  },

  actions: {
    // 获取网站信息
    async fetchWebsite({ commit }) {
      try {
        commit('SET_LOADING', true)
        const website = await websiteApi.getInfo()
        commit('SET_WEBSITE', website)
        return website
      } catch (error) {
        console.error('Failed to fetch website info:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取文章列表
    async fetchArticles({ commit }, params = {}) {
      try {
        commit('SET_LOADING', true)
        const articles = await articleApi.getList(params)
        commit('SET_ARTICLES', articles)
        return articles
      } catch (error) {
        console.error('Failed to fetch articles:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取文章详情
    async fetchArticle({ commit }, articleId: string) {
      try {
        commit('SET_LOADING', true)
        const article = await articleApi.getById(articleId)
        commit('SET_CURRENT_ARTICLE', article)
        
        // 添加到阅读历史
        commit('ADD_TO_READING_HISTORY', articleId)
        
        // 增加阅读量
        await articleApi.addView(articleId)
        
        return article
      } catch (error) {
        console.error('Failed to fetch article:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取最新文章
    async fetchNewsArticles({ commit }) {
      try {
        const articles = await articleApi.getNews()
        commit('SET_NEWS_ARTICLES', articles)
        return articles
      } catch (error) {
        console.error('Failed to fetch news articles:', error)
        throw error
      }
    },
    
    // 获取分类列表
    async fetchCategories({ commit }) {
      try {
        const categories = await categoryApi.getList()
        commit('SET_CATEGORIES', categories)
        return categories
      } catch (error) {
        console.error('Failed to fetch categories:', error)
        throw error
      }
    },
    
    // 获取标签列表
    async fetchTags({ commit }) {
      try {
        const tags = await tagApi.getList()
        commit('SET_TAGS', tags)
        return tags
      } catch (error) {
        console.error('Failed to fetch tags:', error)
        throw error
      }
    },
    
    // 点赞文章
    async likeArticle({ commit, state }, articleId: string) {
      try {
        await articleApi.like(articleId)
        
        // 更新当前文章的点赞数
        if (state.currentArticle && state.currentArticle.id.toString() === articleId) {
          const updatedArticle = {
            ...state.currentArticle,
            likeNum: state.currentArticle.likeNum + 1
          }
          commit('SET_CURRENT_ARTICLE', updatedArticle)
        }
      } catch (error) {
        console.error('Failed to like article:', error)
        throw error
      }
    },
    
    // 切换收藏
    toggleFavorite({ commit }, articleId: string) {
      commit('TOGGLE_FAVORITE', articleId)
    }
  },

  getters: {
    // 网站信息
    websiteInfo: (state) => state.website,
    
    // 是否已加载网站信息
    isWebsiteLoaded: (state) => !!state.website,
    
    // 文章相关
    allArticles: (state) => state.articles,
    currentArticle: (state) => state.currentArticle,
    newsArticles: (state) => state.newsArticles,
    
    // 分类和标签
    allCategories: (state) => state.categories,
    allTags: (state) => state.tags,
    
    // 根据 ID 获取分类
    getCategoryById: (state) => (id: number) => {
      return state.categories.find(cat => cat.id === id)
    },
    
    // 根据 ID 获取标签
    getTagById: (state) => (id: number) => {
      return state.tags.find(tag => tag.id === id)
    },
    
    // UI 状态
    isLoading: (state) => state.loading,
    isSidebarCollapsed: (state) => state.sidebarCollapsed,
    
    // 用户交互
    readingHistory: (state) => state.readingHistory,
    favorites: (state) => state.favorites,
    
    // 检查文章是否已收藏
    isArticleFavorited: (state) => (articleId: string) => {
      return state.favorites.includes(articleId)
    },
    
    // 检查文章是否已阅读
    isArticleRead: (state) => (articleId: string) => {
      return state.readingHistory.includes(articleId)
    }
  }
})

